﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using BL;
using BL.Model.Request;
using Common;
using DAL.Model;
using DevExpress.XtraGrid.Views.Grid;

namespace UI.MainFunctions
{
    public partial class frmTransferManager : Base.DialogViewBase
    {
        #region Privare variables

        private MasterSession _session;
        private readonly TransferController _transferController;

        #endregion

        #region Constructor

        public frmTransferManager()
        {
            InitializeComponent();
            _session = new MasterSession();
            _transferController = new TransferController(_session);
        }

        #endregion

        #region Overided methods

        protected override void InitializeBO()
        {
            base.InitializeBO();

            if(_session == null)
            {
                _session = new MasterSession();
            }
        }

        protected override void PopulateStaticData()
        {
            base.PopulateStaticData();
            LoadCustomers();
            LoadProductCats();
            SetDefaultValues();
        }

        protected override void PopulateData()
        {
            base.PopulateData();

            DateTime fromDate = deFromDate.DateTime > Constant.MinDate
                                    ? deFromDate.DateTime.Date
                                    : Constant.MinDate;
            DateTime toDate = deToDate.DateTime < Constant.MaxDate
                                  ? deToDate.DateTime.Date.AddDays(1)
                                  : Constant.MaxDate;
                                 
            var request = new SearchingTransferRequest
            {
                FromTime = fromDate,
                ToTime = toDate,
                IsPaging = false,
                DocumentNo = txtDocumentNo.Text,
                StockInNo = txtStockInNo.Text,
                ProductCode = txtProductCode.Text
            };

            int customerId;
            if (lueCustomers.EditValue != null && int.TryParse(lueCustomers.EditValue.ToString(), out customerId))
            {
                request.CustomerIds = new List<int> { customerId };
            }
            else
            {
                request.CustomerIds = new List<int> { Constant.AllValue };
            }

            int productCategoryId;
            if (lueProductCat.EditValue != null && int.TryParse(lueProductCat.EditValue.ToString(), out productCategoryId))
            {
                request.ProductCategoryId = productCategoryId;
            }
            else
            {
                request.ProductCategoryId = Constant.AllValue;
            }

            var transfers = _transferController.Search(request);
            dgTransfer.DataSource = null;
            dgTransfer.DataSource = transfers;
            gvTransfer.BestFitColumns();

            var rowCount = transfers.Count;
            for (int i = 0; i < rowCount; i++)
            {
                gvTransfer.ExpandMasterRow(i);
                var detailView = (GridView) gvTransfer.GetDetailView(i, 0);
                detailView.ExpandAllGroups();
            }
        }

        protected override void FormatPrecision()
        {
            PrecisionHelper.FormatCurencyPrecision(gcStockInQuantity,
                                                   gcMassQuantity,
                                                   gcQuantity,
                                                   gcStockOutMassQuantity,
                                                   gcStockOutQuantity);
        }

        #endregion

        #region Private methods 

        private void LoadCustomers()
        {
            var customers = _session.Customers.OrderBy(t=>t.Name).ToList();
            customers.Insert(0, new Customer { Id = -1, Name = string.Empty });
            lueCustomers.Properties.DataSource = customers;
        }

        private void SetDefaultValues()
        {
            deFromDate.DateTime = DateTime.Now.AddDays(-7);
            deToDate.DateTime = DateTime.Now;
        }

        private void LoadProductCats()
        {
            var productCats = _session.ProductCategories.ToList();
            productCats.Insert(0, new ProductCategory { Id = -1, Name = string.Empty });
            lueProductCat.Properties.DataSource = productCats;
        }

        #endregion

        #region Events

        private void spFind_Click(object sender, EventArgs e)
        {
            PopulateData();
        }

        private void spView_Click(object sender, EventArgs e)
        {
            var transfer = (Transfer) gvTransfer.GetRow(gvTransfer.FocusedRowHandle);
            if (transfer== null)
            {
                return;
            }
            var frmTransfer = new frmTransfer(transfer.Id, FormAction.View)
                                  {
                                      MdiParent = MdiParent
                                  };
            frmTransfer.Show();
        }

        private void spAdd_Click(object sender, EventArgs e)
        {

        }

        private void spEdit_Click(object sender, EventArgs e)
        {
            var transfer = (Transfer)gvTransfer.GetRow(gvTransfer.FocusedRowHandle);
            if (transfer == null)
            {
                return;
            }
            var frmTransfer = new frmTransfer(transfer.Id, FormAction.Edit)
                                  {
                                      MdiParent = MdiParent
                                  };
            frmTransfer.Show();
        }

        private void gvTransfer_MasterRowGetChildList(object sender, MasterRowGetChildListEventArgs e)
        {
            var row = (Transfer)gvTransfer.GetRow(e.RowHandle);
            e.ChildList = new BindingSource(row, "TransferDetails");
        }

        private void gvTransfer_MasterRowGetRelationCount(object sender, MasterRowGetRelationCountEventArgs e)
        {
            e.RelationCount = 1;
        }

        private void gvTransfer_MasterRowGetRelationName(object sender, MasterRowGetRelationNameEventArgs e)
        {
            e.RelationName = "TransferDetails";
        }

        private void gvTransfer_MasterRowEmpty(object sender, MasterRowEmptyEventArgs e)
        {
            var row = (Transfer)gvTransfer.GetRow(e.RowHandle);
            e.IsEmpty = row.TransferDetails.Count == 0;
        }

        private void spGenStockOut_Click(object sender, EventArgs e)
        {
            var selectedRows = gvTransfer.GetSelectedRows();
            var customers = selectedRows
                .Select(rowHandle => gvTransfer.GetRow(rowHandle))
                .OfType<Transfer>()
                .Select(t => t.CustomerId)
                .ToArray();
            if (customers.Count() > 2)
            {
                MessageBox.Show("Không thể xuất kho cho nhiều khách hàng cùng lúc",
                                "Thông báo",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }
            var transferIds = selectedRows
                .Select(rowHandle => gvTransfer.GetRow(rowHandle))
                .OfType<Transfer>()
                .Select(t => t.Id)
                .ToArray();

            var stoSession = new MasterSession();
            var stockOutController = new StockOutController(stoSession);
            var stockOut = stockOutController.GenStockOutFromTransfers(transferIds);

            if (stockOut == null ||
                stockOut.StockOutDetails.Count == 0 ||
                stockOut.StockOutDetails.All(t => t.MassQuantity <= 0))
            {
                MessageBox.Show("Phiếu gia công này đã xuất hết số lượng.");
                return;
            }

            var frmStockOut = new frmStockOut(stockOut,
                                              FormAction.New, stoSession)
                                  {
                                      MdiParent = MdiParent
                                  };
            frmStockOut.Show();
        }

        #endregion
    }
}
